/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
#include "glutils.hpp"

#include "GL/glut.h"

//converts screen coords to opengl coords
void screenToGl(const int screenX, const int screenY, const double screenZ,
                float &glX, float &glY, float &glZ)
{
  GLdouble _mx, _my, _mz;
  GLdouble p[16];
  GLdouble m[16];
  GLint v[4];
  glGetDoublev(GL_PROJECTION_MATRIX,p);
  glGetDoublev(GL_MODELVIEW_MATRIX,m);
  glGetIntegerv(GL_VIEWPORT,v);
  
  gluUnProject(screenX,v[3]-screenY,screenZ,m,p,v,&_mx,&_my,&_mz); //NOTICE: subtract window y from window height as opengl has coords the other way
  glX=_mx;
  glY=_my;
  glZ=_mz;
}

//converts opengl coords to screen coords
void glToScreen(const float glX, const float glY, const float glZ,
                int &screenX, int &screenY, double &screenZ)
{
  GLdouble px,py,pz;
  GLdouble p[16], m[16];
  GLint v[4];
  glGetDoublev(GL_PROJECTION_MATRIX,p);
  glGetDoublev(GL_MODELVIEW_MATRIX,m);
  glGetIntegerv(GL_VIEWPORT,v);

  gluProject(glX,glY,glZ,m,p,v,&px,&py,&pz);
  screenX=(int)px;
  screenY=(int)py;
  screenZ=(int)pz;
}

//function for drawing text
void drawText(float x, float y, float z, void *font, const char *string)
{
  const char *c;
  glRasterPos3f(x,y,z);
  for (c=string; *c != '\0'; c++)
  {
    glutBitmapCharacter(font, *c);
  }
}

//get text width in pixels
int getTextWidth(void *font, const char *string)
{
  const char *c;
  int w=0;
  for (c=string; *c != '\0'; c++)
  {
    w=w+glutBitmapWidth(font, *c);
  }
  return w;
}
